import React, { Component } from 'react';
 import {user_login} from "../uilt/api"
 import {connect} from "react-redux"
 import {request_createlist,request_create_cartlist} from "../store/ationCreactor"
class App extends Component {
  constructor(props){
    super(props);
    this.state={
      phone:"",
      pass:""
    }
  }
  hanlechang(e){
  this.setState({
    // 动态把input里面value赋给state里面
    [e.currentTarget.name]:e.currentTarget.value
  },()=>{
    // 想要打印最新数据在state回调里面打印
  })
  }
  login(){
    if(this.state.phone&&this.state.pass){
      user_login(this.state).then((res)=>{
        if(res.data.code===200){
        //  保存用户信息
        localStorage.setItem("userinfo",JSON.stringify(res.data.userinfo))
        // 保存token
        localStorage.setItem("token",res.data.token)
        // 跳转到首页
        this.props.history.push({pathname:"/index"})
        //登录时给redux赋值保持数据库和redux值相同
        this.props.createlist()
        // 登录时使根据id把数据库里面的购物车列表
        this.props.cartlist()
        }else{
          console.log(res.data.msg);
        }
      
      })
    }
  }
  render() {
    return (
      <div className="App">
      <div className='login'>
 <div className="title">
   登录页面
 </div>
 <div className="input">
   <input type="text" name="phone" id="" defaultValue={this.state.phone} onChange={(e)=>{this.hanlechang(e)}}/>
 </div>
 <div className="input">
   <input type="password" name="pass" id="" defaultValue={this.state.pass} onChange={(e)=>{
    this.hanlechang(e)
   }}/>
 </div>
 <div className="input">
   <input type="button" onClick={()=>{this.login()}} value="登录" />
 </div>
   </div>
     </div>
    );
  }
}

export default connect(
  (state)=>{
    return{

    }
  },
  (dispatch)=>{
    return{
      createlist(){
        dispatch(request_createlist())
      },
      cartlist(){
        dispatch(request_create_cartlist())
      }
    }
  }
)(App);